import React, { useState, forwardRef, useImperativeHandle, useCallback, useEffect } from "react";
import { Modal, Alert, Form, Radio, Button, Upload, Switch, message } from "antd";
import { SettingTwoTone, FolderOpenTwoTone } from "@ant-design/icons";
import Iconfont from "@/components/IconFont";
import SetItem from "../../SetItem";
import { CommonModal } from "@/views/components/CommonModal";

import { useExportTask } from "@/views/hooks/useExportTask";
import { useImportTask } from "@/views/hooks/useImportTask";

import ProgressModal from "@/views/components/UIModal/ProgressModal";
import ImportResultModal from "@/views/components/UIModal/ImportResultModal";
import SelectActions from "@/views/components/SelectActions";
import { getImportTemplateUrl, quickQueryLabelGetByCode, quickQueryLabelSaveOrUpdate } from "../../../service";
const { Dragger } = Upload;
// 快捷查询
const SEARCH_TABLE_CODE = "SystemGoods" + "ExcelImportProductsModal" + "unset";
//默认导出设置
const defaultSet = false;

const ExcelImportProductsModal = props => {
	const { createTaskData, isSkuType, onCancel } = props;

	const [visible, setVisible] = useState();

	const [open, setOpen] = useState(false);

	// 导入设置
	const [flex, setFlex] = useState(defaultSet);
	const [childVisible, setChildVisible] = useState(false);
	const [file, setFile] = useState();

	const [radioValue, setRadioValue] = useState(1);

	useEffect(() => {
		console.log('render')
		setOpen(true);
	}, [])

	const { percent, step, result, handleDownload, startTask, clearTimer } = useImportTask();

	useEffect(() => {
		if (step.first === true) {
			setVisible("ProgressModal");
		}
		if (step.second === true) {
			setVisible("ImportResultModal");
		}
		if (step.first === false || step.second === false || step.third === true) {
			onCancel();
		}
	}, [step]);

	const onCancelChild = () => {
		setChildVisible(false);
	};

	const onOkChild = () => {
		setConfig({ flex });
	};

	const onRadioChange = e => {
		setRadioValue(e.target.value);
	};

	const getTemplateUrl = () => {
		getImportTemplateUrl({ taskType: 1202 }).then(res => {
			const { data, msg: msg1, message: msg2 } = res;
			if (data && typeof data === "string" && String(data).startsWith("http")) {
				const f = document.createElement("form");
				document.body.appendChild(f);
				const i = document.createElement("input");
				i.type = "hidden";
				f.appendChild(i);
				f.action = data; //下载的url 地址 f.submit();
				f.submit();
			} else {
				message.error(msg1 || msg2 || "下载文件失败");
			}
		});
	};

	const handleOk = useCallback(() => {
		if (!file) {
			message.warning("请选择要导入的Excel文件");
			return;
		}
		// console.log("isSkuType", isSkuType);
		const businessParam = JSON.stringify({ isCover: Number(flex), isRenew: Number(radioValue) });
		const formData = new FormData();
		formData.append("file", file);
		formData.append("taskType", 1202);
		formData.append("businessParam", businessParam);
		startTask(formData);
	}, [file, radioValue]);

	const renderTitle = () => {
		return (
			<div>
				<span>Excel导入商品资料</span>
				<Button
					type="text"
					icon={<SettingTwoTone />}
					style={{ position: "absolute", right: "60px" }}
					onClick={() => {
						setChildVisible(true);
					}}
				>
					导入设置
				</Button>
			</div>
		);
	};
	// 获取导入设置项
	const getSetConfig = () => {
		quickQueryLabelGetByCode({ code: SEARCH_TABLE_CODE })
			.then(res => {
				const { data, success } = res;
				if (success && data && data.param && typeof data.param === "string") {
					setFlex(JSON.parse(data.param)?.flex);
				} else {
					setFlex(defaultSet);
				}
			})
			.catch(res => {
				console.error("err:", res);
				setFlex(defaultSet);
			});
	};
	// 设置导入设置项
	const setConfig = API_DATA => {
		quickQueryLabelSaveOrUpdate({ code: SEARCH_TABLE_CODE, param: JSON.stringify(API_DATA) })
			.then(res => {
				const { data, success, msg } = res;
				if (success) {
					message.success(msg || "保存成功");
					setChildVisible(false);
				} else {
					message.warning(msg || "保存失败");
				}
			})
			.catch(res => {
				console.log("quickQueryLabelSaveOrUpdate res", res);
			});
	};
	const DraggerProps = {
		name: "file",
		maxCount: 1,
		multiple: true,
		action: "",
		onChange(info) { },
		onDrop(e) { },
		beforeUpload(f) {
			console.log("beforeUpload", f);
			setFile(f);
			return false;
		}
	};
	useEffect(() => {
		getSetConfig();
	}, []);

	console.log(open, 'open')

	return (
		<CommonModal title={{ title: renderTitle() }} visible={open} width="528px" okText="保存" onOk={handleOk} onCancel={onCancel}>
			<Alert
				message="导入支持：修改商品零售价、成本价、虚拟库存等，您可以点击下载模板规范填写商品编码必填，款式编码、商品名未填会按商品编码填充，"
				action={
					<Button
						type="primary"
						ghost
						style={{ marginLeft: 10 }}
						onClick={() => {
							getTemplateUrl({ taskType: 1202 });
						}}
					>
						下载模板
					</Button>
				}
				type="info"
				showIcon
			/>
			<div className="sectionContent" style={{ background: "white", borderLeft: 0, borderTop: 0, padding: 0 }}>
				<div style={{ margin: "15px 0" }}>
					导入时，如果系统存在相同商品编码，则
					<Radio.Group onChange={onRadioChange} value={radioValue} style={{ marginLeft: 5 }}>
						<Radio value={0}>跳过，不处理</Radio>
						<Radio value={1}>全部更新</Radio>
					</Radio.Group>
				</div>
				<Dragger {...DraggerProps}>
					<div style={{ padding: "21.5px 0" }}>
						<p className="ant-upload-drag-icon">
							<Iconfont type="iconExcel" style={{ fontSize: 40 }} />
						</p>
						<p>点击或将文件拖拽到这里上传,只支持Excel文件</p>
						<p className="light-gray">最大50mb，单次最多5000条商品</p>
					</div>
				</Dragger>
			</div>
			<CommonModal
				title={{ title: "导入设置" }}
				width={528}
				open={childVisible}
				onCancel={onCancelChild}
				onOk={onOkChild}
				okText="保存"
			>
				<SetItem
					content="全部更新时，将导入内容覆盖到商品所在的款"
					remark="开启后，如导入款下有多个商品，取第一个商品维护内容覆盖到款"
					onChange={e => {
						setFlex(e);
					}}
					value={flex}
				/>
				<div style={{ height: 24 }}></div>
			</CommonModal>
			<ProgressModal
				visible={visible === "ProgressModal"}
				type="progress"
				percent={percent}
				title="Excel导入商品资料"
				msg="数据提交中..."
				skip
				onCancel={() => {
					{
						onCancel();
						clearTimer();
					}
				}}
			/>
			<ImportResultModal
				visible={visible === "ImportResultModal"}
				result={result}
				handleExportFailed={handleDownload}
				handleCancel={onCancel}
			/>
		</CommonModal>
	);
};

export default ExcelImportProductsModal;
